package com.iplay.实战java高并发程序设计.chapter3.c31;

import java.util.Random;
import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;

/**
 * @author dangwu
 * @since 2021/10/28 4:51 下午
 */
public class CyclicBarrierDemo {
    public static class Soldier implements Runnable {
        private String soldier;
        private final CyclicBarrier cyclicBarrier;

        public Soldier(CyclicBarrier cyclicBarrier, String soldier) {
            this.soldier = soldier;
            this.cyclicBarrier = cyclicBarrier;
        }

        @Override
        public void run() {
            try {
                //等待所有士兵到齐
                cyclicBarrier.await();
                doWork();
                //等待所有士兵完成任务
                cyclicBarrier.await();
                cyclicBarrier.await();
                cyclicBarrier.await();
            } catch (InterruptedException | BrokenBarrierException e) {
                e.printStackTrace();
            }
        }

        void doWork() {
            try {
                int abs = Math.abs(new Random().nextInt() % 10000);
                System.out.println(soldier + ":处理时间是：" + abs);
                Thread.sleep(abs);
                System.out.println(soldier + ":任务完成");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

    public static class BarrierRun implements Runnable {
        boolean flag;
        int n;

        public BarrierRun(boolean flag, int n) {
            this.flag = flag;
            this.n = n;
        }

        @Override
        public void run() {
            if (flag) {
                System.out.println("司令:[士兵" + n + "个，任务完成！]");
            } else {
                System.out.println("司令:[士兵" + n + "个，集合完毕！]");
                flag = true;
            }
        }
    }

    public static void main(String[] args) {
        final int n = 10;
        Thread[] allSoldier = new Thread[n];
        boolean flag = false;
        //CyclicBarrier的await()方法每完成一次，就会调用一次BarrierRun的run()方法
        CyclicBarrier cyclicBarrier = new CyclicBarrier(n, new BarrierRun(flag, n));
        System.out.println("集合队伍!");
        for (int i = 0; i < n; i++) {
            System.out.println("士兵" + i + "报道");
            allSoldier[i] = new Thread(new Soldier(cyclicBarrier, "士兵" + i));
            allSoldier[i].start();
            if (i ==5){
                allSoldier[0].interrupt();
            }
        }
    }

}
